<script setup>
import * as api from "@/api/v-sys-service/sys-manage/role/index.js";
import { listMenuOptions } from "@/api/v-sys-service/sys-manage/menu/index.js";

const emits = defineEmits([
  'query',
  'update:modelValue'
])

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  rowData: {
    type: Object,
    default: () => {}
  },
})
const saveBtnLoading = ref(false)
const authOptionsLoading = ref(false)
const AuthRef = ref()
const authOptions = ref([])

const visible = computed(
    {
      get(){
        return props.modelValue
      },
      set(val){
        emits('update:modelValue',val)
      }
    }
)

const title = computed(()=>{
  return props.rowData.name + ' 权限分配'
})
onMounted(()=>{
  init()
})
const init = () => {
  init_Cache()
}
const init_Cache = async () => {
  authOptionsLoading.value = true
  let resp
  let allRes = []
  resp = await listMenuOptions({flag: false})
  allRes.push(resp)
  const params = {
    roleId: props.rowData.id
  }
  resp = await api.listMenuIds(params)
  allRes.push(resp)
  await Promise.all(allRes).then((res)=>{
    authOptions.value = res[0].data
    res[1].data.forEach(mid=>{
      nextTick(()=>{
        AuthRef.value.setChecked(mid, true, false)
      })
    })
  })
  authOptionsLoading.value = false
}

const sure = async () => {
  const params = {
    roleId: props.rowData.id,
    authIds: [],
  }
  params.authIds = AuthRef.value.getCheckedNodes(false, true).map((node) => node.value)
  saveBtnLoading.value = true
  const {code} = await api.saveAuth(params.roleId,params.authIds)
  saveBtnLoading.value = false
  if (code === 200) {
    visible.value = false
    ElMessage({
      message: '保存成功',
      type: 'success',
    })
    emits('query')
  }
}
</script>

<template>
  <v-dialog v-model="visible" :loading="saveBtnLoading" :title="title" @sure="sure">
    <el-scrollbar v-loading="authOptionsLoading">
      <el-tree
          ref="AuthRef"
          node-key="value"
          show-checkbox
          :data="authOptions"
          :default-expand-all="true"
      >
      </el-tree>
    </el-scrollbar>
  </v-dialog>

</template>

<style scoped lang="scss">

</style>